package ar.com.age.distribuidora.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.com.age.distribuidora.dao.EntregaChequeDao;
import ar.com.age.distribuidora.dominio.EntregaCheque;

@Component
public class EntregaChequeHibernateDao implements EntregaChequeDao{

	private SessionFactory sessionFactory;

	@Autowired(required = true)
	public void setSessionFactory(SessionFactory factory) {
		this.sessionFactory = factory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public EntregaCheque saveOrUpdate(EntregaCheque entregaCheque) {
		if (entregaCheque.getId() == null) {
			getCurrentSession().save(entregaCheque);
		} else {
			getCurrentSession().update(entregaCheque);
		}
		return entregaCheque;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EntregaCheque> getAll() {
		Query query = getCurrentSession().createQuery(
				"from " + EntregaCheque.class.getName());
		return query.list();
	}
	
	@Override
	public void physicalDelete(EntregaCheque entrega){
		
		getCurrentSession().delete(entrega);
				
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<EntregaCheque> find(String codigo, String estado, Date desde, Date hasta, String cliente){
		
		List<EntregaCheque> entregas = null;
		Criteria criteria = getCurrentSession().createCriteria(EntregaCheque.class);
		
		if(codigo != "")
			criteria.add(Restrictions.like("codigo", "%"+codigo+"%"));
		if(estado != "")
			criteria.add(Restrictions.like("estado", "%"+estado+"%"));
		if(cliente != "")
			criteria.createCriteria("cliente", "cliente").add(Restrictions.like("apellido", "%"+cliente+"%"));
		if(desde != null)
			criteria.add(Restrictions.ge("fechaEntrega", desde));
		if(hasta != null)
			criteria.add(Restrictions.le("fechaEntrega", hasta));
		
		entregas = criteria.list();
		
		return entregas;
	}
}
